﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Pg.BioMedics.SDR.Diagnostics
{
    /// <summary>
    /// Performance counter supporting avg timing calculations
    /// </summary>
    public class AverageTimingPerformanceCounter : AverageNumberOfItemsPerformanceCounter
    {
        #region Fields

        private IDictionary<string, Stopwatch> counters = new Dictionary<string, Stopwatch>();        

        #endregion

        #region Constructors

        /// <summary>
        /// Creates instance of avg timing counter
        /// </summary>
        /// <param name="category"></param>
        /// <param name="name"></param>
        internal AverageTimingPerformanceCounter(string category, string name)
            : base(category, name) { }

        #endregion

        #region Methods

        /// <summary>
        /// Starts timing counting
        /// </summary>
        /// <param name="id">counter id</param>
        public void Start(string id)
        {
            lock (this.counters)
            {
                if (this.counters.ContainsKey(id))
                {
                    Stopwatch counter = this.counters[id];
                    if (!counter.IsRunning)
                    {
                        counter.Reset();
                        counter.Start();
                    }
                }
                else
                {
                    Stopwatch counter = new Stopwatch();
                    counter.Start();

                    this.counters.Add(id, counter);
                }
            }
        }

        /// <summary>
        /// Stops timing counting
        /// </summary>
        /// <param name="id">Counter id</param>
        public void Stop(string id)
        {
            lock (this.counters)
            {
                if (this.counters.ContainsKey(id))
                {
                    Stopwatch counter = this.counters[id];
                    if (counter.IsRunning)
                    {
                        counter.Stop();
                        Set(counter.ElapsedMilliseconds);
                    }
                }
            }
        }

        #endregion
    }
}
